package com.example.victory.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

@Slf4j
public class IpHelper {
    /**
     * 检测主机端口是否可连接
     *
     * @param host 主机名或ip
     * @param port 端口号
     * @param port 超时，单位毫秒
     * @return 正常返回true，异常返回false
     */
    public static boolean connect(String host, int port, Integer timeOut) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(host, port), timeOut);
        } catch (IOException e) {
            log.error(e.getMessage() + " host:" + host + ";port:" + port, e);
            return false;
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
        return true;
    }

    /**
     * 是否可访问，有个别环境无法ping通
     *
     * @param host    主机名或ip
     * @param timeOut 超时，单位毫秒
     * @return
     */
    public static boolean reachable(String host, Integer timeOut) {
        try {
            return InetAddress.getByName(host).isReachable(timeOut);
        } catch (UnknownHostException e) {
            log.error(e.getMessage() + " host:" + host);
        } catch (IOException e) {
            log.error(e.getMessage() + " host:" + host);
        }
        return false;
    }
}
